package com.cap.dreamcircle.View;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baoyz.actionsheet.ActionSheet;
import com.bigkoo.pickerview.TimePickerView;
import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Base.BaseActivity;
import com.cap.dreamcircle.Consts.Constants;
import com.cap.dreamcircle.Model.Action.NickNameAction;
import com.cap.dreamcircle.Model.Bean.BaseBean;
import com.cap.dreamcircle.Model.Bean.UserInfoBean;
import com.cap.dreamcircle.Model.IUserModel;
import com.cap.dreamcircle.Model.Impl.UserModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.CommonSubscriber;
import com.cap.dreamcircle.Utils.DeviceUtils;
import com.cap.dreamcircle.Utils.DownloadUtils;
import com.cap.dreamcircle.Utils.GlideLoader;
import com.cap.dreamcircle.Utils.GlideUtils;
import com.cap.dreamcircle.Utils.KeyCounterUtils;
import com.cap.dreamcircle.Utils.PreferenceUtils;
import com.cap.dreamcircle.Utils.RetrofitUploadFileParameterBuilder;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.cap.dreamcircle.Utils.TransformUtils;
import com.jaiky.imagespickers.ImageConfig;
import com.jaiky.imagespickers.ImageSelector;
import com.jaiky.imagespickers.ImageSelectorActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.functions.Action0;

/**
 * Created by liucxu on 2017/7/12.
 */

public class CompleteUserInfoActivity extends BaseActivity {
    @BindView(R.id.layout_nick_name)
    RelativeLayout layout_nick_name;
    @BindView(R.id.tv_nick_name)
    TextView tv_nick_name;
    @BindView(R.id.layout_sex_name)
    RelativeLayout layout_sex_name;
    @BindView(R.id.tv_sex)
    TextView tv_sex;
    @BindView(R.id.layout_birth_name)
    RelativeLayout layout_birth_name;
    @BindView(R.id.tv_birth)
    TextView tv_birth;

    @BindView(R.id.tv_confirm)
    TextView tv_confirm;
    @BindView(R.id.tv_skip)
    TextView tv_skip;
    @BindView(R.id.imv_back)
    ImageView imv_back;
    @BindView(R.id.circle_imv_header)
    CircleImageView circle_imv_header;

    private TimePickerView timePickerView;
    //0:保密 1:男 2:女
    private int sex_index = 0;
    public static final int REQUEST_CODE = 123;
    private File avasterFile;

    private IUserModel userModel;

    private boolean is_wechat_login = false;
    private String wechatHeadImg = "";
    private String wechatNickName = "";
    //1为男性，2为女性
    private int wechatSex = -2;
    private DownloadUtils downloadUtils;

    private boolean modify_user_info = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_complete_user_info;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
    }

    @Override
    public void setupData() {
        userModel = new UserModelImpl();
        downloadUtils = new DownloadUtils();
        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        is_wechat_login = intent.getBooleanExtra("key_wechat", false);
        modify_user_info = intent.getBooleanExtra("modify_user_info", false);
        if (is_wechat_login) {
            wechatHeadImg = intent.getStringExtra("key_wechat_header");
            wechatNickName = intent.getStringExtra("key_wechat_nick");
            wechatSex = intent.getIntExtra("key_wechat_sex", -2);
            tv_nick_name.setText(wechatNickName);
            if (wechatSex == 1) {
                sex_index = 1;
                tv_sex.setText("男");
            } else if (wechatSex == 2) {
                sex_index = 2;
                tv_sex.setText("女");
            } else {
                sex_index = 0;
                tv_sex.setText("保密");
            }
            avasterFile = new File(wechatHeadImg);
            GlideUtils.getInstance().loadSimpleContextVitMap(CompleteUserInfoActivity.this, avasterFile.getPath(), circle_imv_header);
        }
        if (modify_user_info) {
            requestUserInfo();
            imv_back.setVisibility(View.VISIBLE);
            tv_skip.setVisibility(View.GONE);
        }
    }


    private void requestUserInfo() {
        userModel.RequestUserInfo().compose(TransformUtils.<UserInfoBean>defaultSchedulers()).subscribe(new Subscriber<UserInfoBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(UserInfoBean resposne) {
                if (resposne.getCode() == 0) {
                    GlideUtils.getInstance().LoadContextBitmap(CompleteUserInfoActivity.this, Constants.BASE_URL + resposne.getHeadImgUrl(), circle_imv_header, R.mipmap.default_header, R.mipmap.default_header, GlideUtils.LOAD_BITMAP);
                    tv_nick_name.setText(resposne.getNickName());
                    if ("boy".equals(resposne.getSex())) {
                        tv_sex.setText("男");
                        sex_index = 1;
                    } else if ("girl".equals(resposne.getSex())) {
                        tv_sex.setText("女");
                        sex_index = 2;
                    } else {
                        tv_sex.setText("保密");
                        sex_index = 0;
                    }
                    tv_birth.setText(resposne.getBirthDay());
                }
            }
        });
    }


    private boolean validateValue() {
        if (TextUtils.isEmpty(tv_nick_name.getText().toString())) {
            ToastUtils.showShortToast(CompleteUserInfoActivity.this, "请输入昵称");
            return false;
        }
        if (TextUtils.isEmpty(tv_sex.getText().toString())) {
            ToastUtils.showShortToast(CompleteUserInfoActivity.this, "请选择性别");
            return false;
        }
        if (TextUtils.isEmpty(tv_birth.getText().toString())) {
            ToastUtils.showShortToast(CompleteUserInfoActivity.this, "请选择出生日期");
            return false;
        }
        return true;
    }

    private void completeUserInfo() {
        String sex = "";
        if (sex_index == 0) {
            sex = "secret";
        } else if (sex_index == 1) {
            sex = "boy";
        } else {
            sex = "girl";
        }
        RetrofitUploadFileParameterBuilder.newBuilder().cleanParams();
        Map<String, RequestBody> params_requestbody = RetrofitUploadFileParameterBuilder.newBuilder()
                .addParameter("sex", sex)
                .addParameter("birthday", tv_birth.getText().toString())
                .addParameter("nickName", tv_nick_name.getText().toString())
                .addParameter("task", "modifyUserInfo")
                .addParameter("f", "android")
                .addParameter("language", "zh_cn")
                .addParameter("countryCode", "+86")
                .addParameter("version", DeviceUtils.getVersionName())
                .addParameter("userId", PreferenceUtils.GetUserId())
                .addParameter("token", PreferenceUtils.GetUserToken())
                .addParameter("file", avasterFile)
                .bulider();
        userModel.CompleteUserInfo(params_requestbody).compose(TransformUtils.<BaseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                hideProgress();
                if (modify_user_info) {
                    ToastUtils.showShortToast(CompleteUserInfoActivity.this, "成功更新用户信息");
                    App.GetInstance().finishActivity(CompleteUserInfoActivity.this);
                } else {
                    Intent intent = new Intent(CompleteUserInfoActivity.this, MainActivity.class);
                    startActivity(intent);
                    App.GetInstance().finishActivity(CompleteUserInfoActivity.this);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(CompleteUserInfoActivity.this, response.getDesc());
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (modify_user_info) {
            return super.onKeyDown(keyCode, event);
        } else {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {

            } else {
                return super.onKeyDown(keyCode, event);
            }
            return true;
        }
    }

    @OnClick({R.id.imv_back, R.id.tv_confirm, R.id.tv_skip, R.id.layout_nick_name, R.id.layout_sex_name, R.id.layout_birth_name, R.id.circle_imv_header})
    void doClickButtons(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.imv_back:
                App.GetInstance().finishActivity(CompleteUserInfoActivity.this);
                break;
            case R.id.tv_confirm:
                KeyCounterUtils.SendKeyCounter("198e59129d7d4af0bdf842c94e63cabc");
                if (validateValue()) {
                    completeUserInfo();
                }
                break;
            case R.id.tv_skip:
                Intent intent_main = new Intent(CompleteUserInfoActivity.this, MainActivity.class);
                startActivity(intent_main);
                App.GetInstance().finishActivity(CompleteUserInfoActivity.this);
                break;
            case R.id.layout_nick_name:
                KeyCounterUtils.SendKeyCounter("3536f6a77c4440db8499f02ae87ee765");
                Intent intent = new Intent(CompleteUserInfoActivity.this, NickNameActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_sex_name:
                ActionSheet.createBuilder(this, getSupportFragmentManager())
                        .setCancelButtonTitle("取消")
                        .setOtherButtonTitles("保密", "男", "女")
                        .setCancelableOnTouchOutside(true)
                        .setListener(new ActionSheet.ActionSheetListener() {
                            @Override
                            public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                            }

                            @Override
                            public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                                KeyCounterUtils.SendKeyCounter("9f2a6177f32047928b0f867fe20cb2b1");
                                sex_index = index;
                                if (sex_index == 0) {
                                    tv_sex.setText("保密");
                                } else if (sex_index == 1) {
                                    tv_sex.setText("男");
                                } else if (sex_index == 2) {
                                    tv_sex.setText("女");
                                }
                            }
                        }).show();
                break;
            case R.id.layout_birth_name:
                KeyCounterUtils.SendKeyCounter("e45e6327cef54418875a0a75055869d7");
                if (timePickerView == null) {
                    Calendar current = Calendar.getInstance();
                    Calendar startDate = Calendar.getInstance();
                    Calendar endDate = Calendar.getInstance();
                    //正确设置方式 原因：注意事项有说明
                    startDate.set(1900, 0, 1);
                    endDate.set(2020, 11, 31);
                    timePickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {//选中事件回调
                            if((new Date().getTime())>=date.getTime()){
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                String select_date = sdf.format(date);
                                tv_birth.setText(select_date);
                            }
                            else{
                                ToastUtils.showShortToast(CompleteUserInfoActivity.this,"请选择正确的时间");
                            }
                        }
                    })
                            .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                            .setCancelText("取消")//取消按钮文字
                            .setSubmitText("确定")//确认按钮文字
                            .setContentSize(18)//滚轮文字大小
                            .setTitleSize(18)//标题文字大小
                            .setTitleText("选择出生日期")//标题文字
                            .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                            .isCyclic(true)//是否循环滚动
                            .setTitleColor(Color.WHITE)//标题文字颜色
                            .setSubmitColor(Color.WHITE)//确定按钮文字颜色
                            .setCancelColor(Color.WHITE)//取消按钮文字颜色
                            .setTitleBgColor(0xff1e3550)//标题背景颜色 Night mode
                            .setBgColor(0xff1e3550)//滚轮背景颜色 Night mode
                            .setTextColorCenter(0xffffffff)
                            .setTextColorOut(0xffffffff)
                            .setDate(current)// 如果不设置的话，默认是系统时间*/
                            .setRangDate(startDate, endDate)//起始终止年月日设定
                            .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                            .isDialog(false)//是否显示为对话框样式
                            .build();
                }
                timePickerView.show();
                break;
            case R.id.circle_imv_header:
                KeyCounterUtils.SendKeyCounter("3d9c39a0001445299fbb0c5ef5caf071");
                ImageConfig imageConfig = new ImageConfig.Builder(
                        new GlideLoader())
                        .steepToolBarColor(0xff1e3550)
                        .titleBgColor(0xff1e3550)
                        .titleSubmitTextColor(getResources().getColor(R.color.white))
                        .titleTextColor(getResources().getColor(R.color.white))
                        // 开启单选   （默认为多选）
                        .singleSelect()
                        // 裁剪 (只有单选可裁剪)
                        .crop(1, 1, 300, 300)
                        // 开启拍照功能 （默认关闭）
                        .showCamera()
                        // 拍照后存放的图片路径（默认 /temp/picture）
                        .filePath("/dreamcircle/pic")
//                        //设置显示容器
//                        .setContainer(llContainer)
                        .requestCode(REQUEST_CODE)
                        .build();
                ImageSelector.open(CompleteUserInfoActivity.this, imageConfig);
                break;
        }
    }


    public void onEvent(NickNameAction nickNameAction) {
        tv_nick_name.setText(nickNameAction.getNickName());
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
            if ((pathList != null) && (pathList.size() == 1)) {
                avasterFile = new File(pathList.get(0));
                GlideUtils.getInstance().loadSimpleContextVitMap(CompleteUserInfoActivity.this, pathList.get(0), circle_imv_header);
            }
        }
    }
}
